#include "model/mysqlhelper.h"
#include <mysql/mysql.h>


int initMysql_7th() {
	if (mysql_library_init(0, NULL, NULL)) {
		fprintf(stderr, "could not initialize MySQL client library\n");
		exit(1);
	}
	return 0;
}

int getConnect_7th(MYSQL **conn) {
	if (conn == NULL)
		return -1;
	*conn = mysql_init(NULL);
	MYSQL *ret =
		mysql_real_connect(*conn, MYSQL_HOST_7TH, MYSQL_USERNAME_7TH,
						   MYSQL_PASSWD_7TH, MYSQL_DB_7TH, MYSQL_PORT_7TH, NULL, 0);

	if (ret != *conn) {
		mysql_errno(*conn);
		printf("mysql_real_conn error\n");
		return -1;
	}
	return 0;
}

int closeConnect_7th(MYSQL *conn) {
	if (conn == NULL)
		return -1;
	mysql_close(conn);
	return 0;
}

int closeMysql_7th() {
	mysql_library_end();
	return 0;
}

void initinBindParams(MYSQL_BIND *inbind, int mysql_type, void *buffer,
					  unsigned long len) {
	inbind->buffer_type = mysql_type;
	inbind->buffer = buffer;
	inbind->buffer_length = len;
}

void initBindResult(MYSQL_BIND *outbind, int mysql_type, void *res_buffer,
					unsigned long need_size, bool *is_null,
					unsigned long *get_szie, bool *error) {
	if (outbind == NULL)
		return;
	outbind->buffer_type = mysql_type;
	outbind->buffer = res_buffer;
	if (need_size > 0)
		outbind->buffer_length = need_size;
	outbind->is_null = is_null;
	outbind->length = get_szie;
	outbind->error = error;
}

int initStmt(MYSQL_STMT **stmt, MYSQL *conn, char *sql) {
	*stmt = mysql_stmt_init(conn);

	if (*stmt == NULL) {
		fprintf(stderr, "mysql_stmt_init() failed: %s\n", mysql_error(conn));
		return 1;
	}

	if (mysql_stmt_prepare(*stmt, sql, strlen(sql))) {
		fprintf(stderr, "mysql_stmt_prepare() failed: %s\n",
				mysql_stmt_error(*stmt));
		mysql_stmt_close(*stmt);
		return 1;
	}
	return 0;
}
